import json

from django.contrib.auth import login
from django.shortcuts import render
from django.views import View

from utils.json_fun import to_json_data
from utils.response_code import Code, error_map
from .forms import RegisterForm
from .models import Users

# Create your views here.


class RegisterView(View):
    """
    用户注册
    url: users/register/
    """
    def get(self, request):

        return render(request, 'users/register.html')

    def post(self, request):
        json_data = request.body
        if not json_data:
            return to_json_data(errno=Code.PARAMERR, errmsg=error_map[Code.PARAMERR])
        dict_data = json.loads(json_data.decode('utf-8'))

        form = RegisterForm(data=dict_data)
        if form.is_valid():
            username = form.cleaned_data.get('username')
            password = form.cleaned_data.get('password')
            mobile = form.cleaned_data.get('mobile')

            user = Users.objects.create_user(username=username, password=password, mobile=mobile)
            login(request, user)
            return to_json_data(errmsg='恭喜您，注册成功')
        else:
            err_msg_list = []
            for item in form.errors.get_json_data().values():
                err_msg_list.append(item[0].get('message'))
            err_msg_str = '/'.join(err_msg_list)

            return to_json_data(errno=Code.PARAMERR, errmsg=err_msg_str)


class LoginView(View):
    """
    用户登陆
    url: users/login/
    """
    def  get(self,request):
        return render(request,'users/login.html')



class LogoutView(View):
    """
    用户登出
    url: users/logout/
    """
    pass
